﻿using AbstractProducts;
using Jira.JiraSoap;
using log4net;
using Utilities;

namespace Jira
{
    internal sealed class JiraProductLink
    {
        private static readonly ILog s_Log = LogManager.GetLogger("Jira.JiraProductLink");

        private readonly RemoteIssue m_ProductLinkIssue;
        private readonly ProductRef m_ProductRef;
        private readonly JiraProductLinkConfig m_JiraProductLinkConfig;

        internal JiraProductLink(JiraConnection jiraConnection, RemoteIssue productLinkIssue)
        {
            s_Log.InfoFormat("Reading {0}", productLinkIssue.key);

            m_ProductLinkIssue = productLinkIssue;

            // the product ref is retrieved verbatim from the summary
            m_ProductRef = new ProductRef(productLinkIssue.summary);

            // the config is parsed from the description
            if (productLinkIssue.description != null)
            {
                m_JiraProductLinkConfig = JiraJsonSerializer.Populate<JiraProductLinkConfig>(productLinkIssue.description);
            }
            else
            {
                m_JiraProductLinkConfig = new JiraProductLinkConfig();
            }

            // Reformat and remove dead properties if required.
            string prettyDescription = JiraJsonSerializer.Serialize(m_JiraProductLinkConfig);
            if (productLinkIssue.description != prettyDescription.Replace("\r", ""))
            {
                RemoteFieldValue fieldValue = new RemoteFieldValue { id = "description", values = new[] { prettyDescription } };
                jiraConnection.Client.updateIssue(jiraConnection.Token, productLinkIssue.key, new[] { fieldValue });
                s_Log.InfoFormat("Prettified description for {0}", productLinkIssue.key);
            }
        }

        internal ProductRef ProductRef
        {
            get { return m_ProductRef; }
        }

        internal string ProjectKey
        {
            get { return m_ProductLinkIssue.project; }
        }

        internal RemoteIssue CreatePrototypeIssue()
        {
            // Clone prototype from the product link issue
            RemoteIssue prototypeIssue = SerializationCloner.Clone(m_ProductLinkIssue);

            // Clear these because they uniquely identify the product link issue
            prototypeIssue.id = null;
            prototypeIssue.key = null;

            // Clear these because they're magic for product links
            prototypeIssue.summary = null;
            prototypeIssue.description = null;

            return prototypeIssue;
        }

        internal JiraProductLinkConfig JiraProductLinkConfig
        {
            get { return m_JiraProductLinkConfig; }
        }
    }
}
